<?php
namespace app\admin\model;

use app\admin\enum\ScopeEnum;
use think\model\concern\SoftDelete;
use app\admin\model\{SystemRoleMenu, SystemRoleAdmin};
use think\facade\Db;

class SystemRole extends BaseModel
{
    use SoftDelete;
    protected $deleteTime = 'delete_time';

    protected $hidden = ['user_id'];
    
    public function getStatusAttr($value)
    {
        $status = [0 => '禁用', 1 => '正常'];
        return $status[$value];
    }

    public function roles()
    {
        return $this->belongsToMany('SystemRole', 'system_role_menu', 'role_id', 'menu_id');
    }

    public function menus()
    {
        return $this->belongsToMany('SystemMenus', 'system_role_menu', 'menu_id', 'role_id');
    }

    public static function roleToMenus()
    {
        $role_id = SystemRoleAdmin::role(self::tokenToUid());
        return self::where('id', '=', $role_id)->with(['menus' => function($query) {
            $query->getQuery()->where('system_menus.is_show', '=', 1)->order('system_menus.sort', 'desc');
        }])->select()->toArray();
    }

    public static function roleDetail()
    {
        return self::where('status', '=', 1)->order('id desc')->field('id, role_name')->select();
    }

    public static function roleList($param)
    {
        $model = new self;
        if($param['search'] != 'null') {
            $model = $model->where('role_name', 'LIKE', "%{$param['search']}%");
        }

        switch($param['state']) {
            case 1:
                $model = $model->where('status', '=', 1);
                break;
            case 2:
                $model = $model->where('status', '=', 0);
                break;
            case 3:
                $model = $model->onlyTrashed();
                break;  
            default:
                $model = $model->withTrashed();
                break;
        }

        $result = $model->with(['menus' => function($query) {
            $query->getQuery()->field('system_menus.menu_name');
        }])->page($param['page'], $param['pageSize'])->order('id desc')->select()->toArray(); 

        foreach($result as $index => &$item){
            $rules_name = '';
            $rules = [];
            foreach($item['menus'] as $value){
                $rules_name .= '、'. $value['menu_name'];
                array_push($rules, $value['pivot']['menu_id']);
            }
            $item['rules_name'] = mb_substr($rules_name, 1, strlen($rules_name), 'UTF-8');
            $item['rules'] = $rules;
            unset($result[$index]['menus']);
        }
        
        $total = $model->count();
        $bage = self::createBage($result);

        return [
            'bage' => $bage,
            'list' => $result,
            'total' => $total
        ];

    }

    public static function roleCreateOrUpdate($data)
    {
        Db::startTrans();
        try {
            $data['status'] == true ? 1 : 0;
            $rules = $data['rules'];
            unset($data['rules']);
            unset($data['delete_time']);

            $systemRole = new self;
            $SystemRoleMenu = new SystemRoleMenu();

            if(isset($data['id'])){
                unset($data['rules_name']);
                $systemRole = $systemRole::find($data['id']);
                $SystemRoleMenu->where('role_id', '=', $systemRole->id)->delete();
            }else{
                $data['user_id'] = self::tokenToUid();
            }

            $systemRole->save($data);

            $role = [];
            foreach($rules as $item){
                $list['role_id'] = $systemRole->id;
                $list['menu_id'] = $item;
                $role[] = $list;
            }
            
            $SystemRoleMenu->saveAll($role);

            Db::commit();

            return true;
        } catch (\Throwable $th) {
            Db::rollback();
            throw $th;
        }
    }

    public static function menuRole()
    {
        $scope = self::tokenToScope();

        if($scope == ScopeEnum::Super){
            return self::where('status', '=', 1)->order('id desc')->field('id,role_name')->select();
        }else{
            $uid = self::tokenToUid();
            return self::where('user_id', $uid)->where('status', '=', 1)->order('id desc')->field('id,role_name')->select();
        }
    }

    public static function delRole($id)
    {
        $data = self::onlyTrashed()->find($id);
        if($data)
            return $data->restore();
        else
            return self::destroy($id);
    }

    public static function createBage($data)
    {
        $enable = $disable = $del = 0;
        foreach($data as $item){
            if($item['status'] == '正常') 
                $enable ++;
            else
                $disable ++;

            if($item['delete_time']) $del ++;
        }

        return [
            [
                'name' => '全部', 
                'unit' => '个',
                'number' => count($data)
            ],
            [
                'name' => '开启', 
                'unit' => '个',
                'number' => $enable
            ],
            [
                'name' => '禁用', 
                'unit' => '个',
                'number' => $disable
            ],
            [
                'name' => '删除', 
                'unit' => '个',
                'number' => $del
            ]
        ];
    }
}